﻿using System;
using System.Collections.Generic;
using System.Linq;
using RimWorld;
using Verse;
using Verse.AI;
using Verse.AI.Group;

namespace ARMIR {
    /// <summary>
    /// 袭击
    /// 袭击会在地图边缘生成七名敌人，一个boss六个盾卫。boss的逻辑是肘击殖民地里的每一个人，一个个来。六个盾卫的ai是跟着boss边上围着，呈六边形。
    /// 额外一点的逻辑就是，如果盾卫寄了一个就会亡语，强行让boss进入放大招也就是那个asyourwish的hediff给到boss
    /// </summary>
    public class IncidentWorker_Raid_Attack_incidentShieldTeam : IncidentWorker_Raid {
        public IncidentWorker_Raid_Attack_incidentShieldTeam() {
        }


        /// <summary>
        /// 设置袭击者的阵营
        /// </summary>
        /// <param name="parms"></param>
        /// <returns></returns>
        protected override bool TryResolveRaidFaction(IncidentParms parms) {
            // 获取设置的小人
            var pawns = SetPawns();
            // 获取boss小人
            var bossPawn = pawns[0];
            // 判断boss实例是否存在, 不存在就不生成袭击
            if (bossPawn == null) {
                Log.Error("Boss实例不存在");
                return false;
            }

            // 获取BOSS阵营
            var bossFaction = bossPawn.Faction;
            // 判断阵营是否存在, 不存在就不生成袭击
            if (bossFaction == null) {
                Log.Error("Boss阵营为空");
                return false;
            }

            return true;
        }

        /// <summary>
        /// 设置袭击策略
        /// </summary>
        /// <param name="parms"></param>
        /// <param name="groupKind"></param>
        public override void ResolveRaidStrategy(IncidentParms parms, PawnGroupKindDef groupKind) {
            Map map = parms.target as Map;
            if (map == null) {
                // 目标不是地图时，使用默认策略
                parms.raidStrategy = RaidStrategyDefOf.ImmediateAttack;
                return;
            }

            // 自定义策略筛选：只允许特定策略
            List<RaidStrategyDef> availableStrategies = DefDatabase<RaidStrategyDef>.AllDefs
                .Where(def =>
                        def.defName == "ShieldedAssault" || // 自定义护盾突击策略
                        def.defName == "Flank" // 允许侧翼包抄
                )
                .Where(def => def.Worker.CanUseWith(parms, groupKind)) // 检查策略是否适用
                .ToList();

            // 按权重随机选择一个可用策略
            if (availableStrategies.TryRandomElementByWeight(
                    def => def.Worker.SelectionWeightForFaction(map, parms.faction, parms.points),
                    out RaidStrategyDef selectedStrategy)) {
                parms.raidStrategy = selectedStrategy;
            }
            else {
                // 无可用策略时，使用默认并报错
                Log.Warning("No valid shield team strategy found, using default.");
                parms.raidStrategy = RaidStrategyDefOf.ImmediateAttack;
            }
        }

        /// <summary>
        /// 设置袭击标题 TODO 为啥覆写没用
        /// </summary>
        /// <param name="parms"></param>
        /// <returns></returns>
        protected override string GetLetterLabel(IncidentParms parms) {
            return "护盾小队袭击";
        }

        /// <summary>
        /// 设置袭击描述 TODO 为啥覆写没用
        /// </summary>
        /// <param name="parms"></param>
        /// <param name="pawns"></param>
        /// <returns></returns>
        protected override string GetLetterText(IncidentParms parms, List<Pawn> pawns) {
            return "啊哈";
        }

        protected override LetterDef GetLetterDef() {
            return new LetterDef();
        }

        protected override string GetRelatedPawnsInfoLetterText(IncidentParms parms) {
            return "";
        }

        protected override void ResolveRaidPoints(IncidentParms parms) {
        }

        /// <summary>
        /// 设置袭击任务
        /// </summary>
        /// <param name="parms"></param>
        /// <returns></returns>
        protected override bool TryExecuteWorker(IncidentParms parms) {
            // 获取地图
            var map = (Map)parms.target;
            // 获取设置的小人
            var pawns = SetPawns();
            // 设置边缘步行进入
            parms.raidArrivalMode = PawnsArrivalModeDefOf.EdgeWalkIn;
            // 计算世界中心
            if (!parms.raidArrivalMode.Worker.TryResolveRaidSpawnCenter(parms)) {
                // 若计算失败，手动指定一个边缘位置作为保底
                parms.spawnCenter = CellFinder.RandomEdgeCell(map);
                Log.Warning("自动计算 spawn 中心失败，使用手动边缘位置");
            }

            // 创建一个Lord（管理者）
            Lord lord = LordMaker.MakeNewLord(parms.faction, new LordJob_AssaultColony(parms.faction, true), map);
            // 让Lord去管理小人
            lord.AddPawns(pawns);
            // 生成小人
            parms.raidArrivalMode.Worker.Arrive(pawns, parms);
            // 获取BOSS
            var bossPawn = pawns[0];
            // 循环非BOSS小人，给小人设置job
            for (int i = 1; i < pawns.Count; i++) {
                // 获取小人
                Pawn pawn = pawns[i];
                Job job = JobMaker.MakeJob(JobDefOf_Custom.FollowBossPawn, bossPawn);
                job.targetA = bossPawn;
                job.targetB = pawn;
                pawn.jobs.StartJob(job, JobCondition.InterruptForced);
                // pawn.jobs.TryTakeOrderedJob(job);
            }

            var lookTargets = new LookTargets(pawns);
            // 设置袭击音效, 和发送信件
            SendStandardLetter(parms, lookTargets);
            return true;
        }

        /// <summary>
        /// 自定义触发条件
        /// </summary>
        /// <param name="parms"></param>
        /// <returns></returns>
        /*protected override bool CanFireNowSub(IncidentParms parms) {
            return base.CanFireNowSub(parms);
        }*/

        /// <summary>
        /// 自定义袭击者
        /// </summary>
        /// <returns>袭击者队列</returns>
        private List<Pawn> SetPawns() {
            // 创建一个袭击者队列
            var pawns = new List<Pawn>();
            // 创建BOSS
            var bossPawn = RosmontisGenerator.GenerateRosmontis(Faction.OfPlayer);
            // 添加把BOSS添加到袭击者队列中
            pawns.Add(bossPawn);
            // 循环生成小兵，循环几次取决于要生成几个小兵
            for (var i = 0; i < 6; i++) {
                // 创建盾兵
                Pawn pawn = PawnGenerator.GeneratePawn(new PawnGenerationRequest(
                    kind: PawnKindDefOf.Colonist, // 使用殖民者类型
                    faction: bossPawn.Faction, // 和boss同阵营
                    context: PawnGenerationContext.NonPlayer, // 生成上下文
                    fixedGender: Gender.Female // 固定性别为女性
                ));
                // 把盾兵添加到袭击者队列中
                pawns.Add(pawn);
            }

            return pawns;
        }
    }
}